import { Component, ChangeDetectorRef } from "@angular/core";
import {
  IonicPage,
  NavController,
  NavParams,
  ActionSheetController,
  LoadingController,
  AlertController
} from "ionic-angular";
import { EmergencyRescueBean } from "./bean/emergencyRescue.bean";
import { WorkSumPage } from "../work-sum/work-sum";
import { CommonFunc } from "../../providers/commonFunc";
import { HttpService } from "../../providers/http.service";
import * as moment from "moment";
import {
  FileUploadOptions,
  FileTransferObject,
  FileTransfer
} from "@ionic-native/file-transfer";
import { CameraOptions, Camera } from "@ionic-native/camera";
import { PhotoViewer } from "@ionic-native/photo-viewer";
import { appConfig } from "../../providers/config";
import { HomePage } from "../home/home";
@Component({
  selector: "page-emergencyrescue",
  templateUrl: "emergencyrescue.html"
})
export class EmergencyrescuePage {
  private isDisabled: boolean = false;
  private time1 = new Date().getTime() + "1";
  private time2 = new Date().getTime() + "2";
  private time3 = new Date().getTime() + "3";
  securityAdminSignUrl: string;
  rescueUserSignUrl: string;
  rescueUserSignUrl2: string;
  private images: any[] = [];
  appConfig = appConfig;
  rescuePartyName: string;
  canSubmit = false;
  private emergencyRescueBean: EmergencyRescueBean = new EmergencyRescueBean();
  private humanReason:any;
  private outsideReason:any;
  private doorSystem:any;
  private tractionSystem:any;
  private guideSystem:any;
  private bridgeCabin:any;
  private controlSystem:any;
  private electricSystem:any;
  private safeRefinement:any;

  private humanReasonParam:any;
  private outsideReasonParam:any;
  private doorSystemParam:any;
  private tractionSystemParam:any;
  private guideSystemParam:any;
  private bridgeCabinParam:any;
  private controlSystemParam:any;
  private electricSystemParam:any;
  private safeRefinementParam:any;



  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public commonFunc: CommonFunc,
    public httpService: HttpService,
    private camera: Camera,
    private actionSheet: ActionSheetController,
    private photoViewer: PhotoViewer,
    private transfer: FileTransfer,
    public cd: ChangeDetectorRef,
    private loadc: LoadingController,
    private alerc: AlertController
  ) {
    this.emergencyRescueBean.elevatorId = this.navParams.get("elevatorId");
      this.emergencyRescueBean.elevatorId = "2896";
    this.emergencyRescueBean.elevatorNum = this.navParams.get("elevatorNum");
      this.emergencyRescueBean.elevatorNum = "30103205062014030059";


  }
  ionViewWillEnter(){
      this.initfault();
  }

  initfault(){
      this.httpService.initfault({}).subscribe(data => {
          if (data.status == 200) {
            this.humanReason = data.data.one;
            this.outsideReason = data.data.two;
            this.doorSystem = data.data.three;
            this.tractionSystem = data.data.four;
            this.guideSystem = data.data.five;
            this.bridgeCabin  = data.data.six;
            this.controlSystem = data.data.seven;
            this.electricSystem = data.data.eight;
            this.safeRefinement=  data.data.nine;
          }
      });
  }


  submit() {
    console.log(this.humanReasonParam.join(","));

    if (!this.canSubmit) {
      const alertcc = this.alerc.create({
        // title: '',
        subTitle: "救援实施单位不正确，请重新输入",
        buttons: ["确定"]
      });
      alertcc.present();
      return;
    }
    if (!this.securityAdminSignUrl || !this.rescueUserSignUrl) {
      let toas = this.commonFunc.showToast({
        message: "请签名!",
        duration: 3000,
        position: "top"
      });
      toas.present();
      return;
    }
    if (this.images.length <= 0) {
      let toas = this.commonFunc.showToast({
        message: "拍些照片吧",
        duration: 3000,
        position: "top"
      });
      toas.present();
      return;
    }
    this.emergencyRescueBean.rescuePartyName = this.rescuePartyName;
    this.emergencyRescueBean.picUrl = this.images.join(",");
    this.emergencyRescueBean.securityAdminSignUrl = this.securityAdminSignUrl;
    this.emergencyRescueBean.rescueUserSignUrl = this.rescueUserSignUrl;
    this.emergencyRescueBean.rescueUserSignUrl2 = this.rescueUserSignUrl2;
    if (this.emergencyRescueBean.protective) {
      this.emergencyRescueBean.protective = this.emergencyRescueBean.protective.toString();
    }
    if (this.isDisabled == true) {
      this.emergencyRescueBean.noCasualties = "1";
      if (
        !this.emergencyRescueBean.deathNum &&
        !this.emergencyRescueBean.minorWoundNum &&
        !this.emergencyRescueBean.injuredNum
      ) {
        let toas = this.commonFunc.showToast({
          message: "请填写伤亡情况",
          duration: 3000,
          position: "top"
        });
        toas.present();
        return;
      }
      if (!this.emergencyRescueBean.deathNum) {
        this.emergencyRescueBean.deathNum = "0";
      }
      if (!this.emergencyRescueBean.minorWoundNum) {
        this.emergencyRescueBean.minorWoundNum = "0";
      }
      if (!this.emergencyRescueBean.injuredNum) {
        this.emergencyRescueBean.injuredNum = "0";
      }
    } else {
      this.emergencyRescueBean.noCasualties = "0";
      this.emergencyRescueBean.deathNum = "0";
      this.emergencyRescueBean.minorWoundNum = "0";
      this.emergencyRescueBean.injuredNum = "0";
    }
    this.emergencyRescueBean.receivedTime = this.emergencyRescueBean.receivedTime
      .replace(/-/g, "")
      .replace(/T/g, "")
      .replace(/Z/g, "")
      .replace(/:/g, "");
    this.emergencyRescueBean.arrivedTime = this.emergencyRescueBean.arrivedTime
      .replace(/-/g, "")
      .replace(/T/g, "")
      .replace(/Z/g, "")
      .replace(/:/g, "");
    this.emergencyRescueBean.rescueEndTime = this.emergencyRescueBean.rescueEndTime
      .replace(/-/g, "")
      .replace(/T/g, "")
      .replace(/Z/g, "")
      .replace(/:/g, "");

    let load = this.loadc.create({
      spinner: appConfig.spinner,
      duration: appConfig.timeout
    });

    load.present();

    this.emergencyRescueBean.humanReasonParam = this.humanReasonParam.join(",");
    this.emergencyRescueBean.outsideReasonParam = this.outsideReasonParam.join(",");
    this.emergencyRescueBean.doorSystemParam = this.doorSystemParam.join(",");
    this.emergencyRescueBean.tractionSystemParam = this.tractionSystemParam.join(",");
    this.emergencyRescueBean.guideSystemParam = this.guideSystemParam.join(",");
    this.emergencyRescueBean.bridgeCabinParam = this.bridgeCabinParam.join(",");
    this.emergencyRescueBean.controlSystemParam = this.controlSystemParam.join(",");
    this.emergencyRescueBean.electricSystemParam = this.electricSystemParam.join(",");
    this.emergencyRescueBean.safeRefinementParam = this.safeRefinementParam.join(",");

    this.httpService
      .emergencyRescueAdd(this.emergencyRescueBean)
      .subscribe(data => {
        load.dismiss();
        if (data.status == 200) {
          const alertcc = this.alerc.create({
            // title: '',
            subTitle: "提交成功",
            buttons: ["确定"]
          });
          alertcc.present();
          this.navCtrl.setRoot(HomePage).then(() => {
            window["jQuery"](`#` + this.time1).remove();
            window["jQuery"](`#` + this.time2).remove();
            window["jQuery"](`#` + this.time3).remove();
          });
        } else {
          const alertcc = this.alerc.create({
            // title: '',
            subTitle: "提交失败，请重试",
            buttons: ["确定"]
          });
          alertcc.present();
        }
      });
  }

  getSafeImgUrl(param) {
    this.securityAdminSignUrl = param.imageDate;
    this.emergencyRescueBean.suredTime = moment(new Date()).format(
      "YYYYMMDDHHmmss"
    );
  }

  getMaintImgUrl(param) {
    this.rescueUserSignUrl = param.imageDate;
    this.emergencyRescueBean.signedTime = moment(new Date()).format(
      "YYYYMMDDHHmmss"
    );
  }

  getMaintImgUrl2(param) {
    this.rescueUserSignUrl2 = param.imageDate;
    this.emergencyRescueBean.signedTime = moment(new Date()).format(
      "YYYYMMDDHHmmss"
    );
  }
  doCamera(i) {
    let options: CameraOptions = {
      quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
      // encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      targetWidth: 1500,
      targetHeight: 1500,
      correctOrientation: true
    };
    this.camera.getPicture(options).then(
      imageData => {
        const options: FileUploadOptions = {};
        let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
        //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
        options.fileKey = "file";
        options.fileName = "test.jpg";
        options.mimeType = "image/jpeg";
        const fileTransfer: FileTransferObject = this.transfer.create();
        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
          let aa = JSON.parse(restul["response"]);
          if (aa["status"] == 200) {
            if (aa["data"].length > 0) {
              if (i == "c") {
                this.images.push(aa["data"]);
              } else {
                this.images[i] = aa["data"];
              }
            }
          }
          this.cd.detectChanges();
        });
      },
      err => {
        // Handle error
      }
    );
  }

  presentActionSheet(i) {
    let buttonList: any = [];
    buttonList.push({
      text: "拍照",
      role: "拍照",
      handler: () => {
        let options: CameraOptions = {
          quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
          // encodingType: this.camera.EncodingType.JPEG,
          mediaType: this.camera.MediaType.PICTURE,
          targetWidth: 1500,
          targetHeight: 1500,
          correctOrientation: true
        };
        this.camera.getPicture(options).then(
          imageData => {
            const options: FileUploadOptions = {};
            let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
            //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
            options.fileKey = "file";
            options.fileName = "test.jpg";
            options.mimeType = "image/jpeg";
            const fileTransfer: FileTransferObject = this.transfer.create();
            fileTransfer.upload(imageData, serverUrl, options).then(restul => {
              let aa = JSON.parse(restul["response"]);
              if (aa["status"] == 200) {
                if (aa["data"].length > 0) {
                  if (i == "c") {
                    this.images.push(aa["data"]);
                  } else {
                    this.images[i] = aa["data"];
                  }
                }
              }
              this.cd.detectChanges();
            });
          },
          err => {
            // Handle error
          }
        );
      }
    });
    buttonList.push({
      text: "从相册选择照片",
      role: "从相册选择照片",
      handler: () => {
        let options: CameraOptions = {
          sourceType: 0,
          quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
          // encodingType: this.camera.EncodingType.JPEG,
          mediaType: this.camera.MediaType.PICTURE,
          targetWidth: 1500,
          targetHeight: 1500,
          correctOrientation: true
        };
        this.camera.getPicture(options).then(
          imageData => {
            const options: FileUploadOptions = {};
            let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
            //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
            options.fileKey = "file";
            options.fileName = "test.jpg";
            options.mimeType = "image/jpeg";
            const fileTransfer: FileTransferObject = this.transfer.create();
            fileTransfer.upload(imageData, serverUrl, options).then(restul => {
              let aa = JSON.parse(restul["response"]);
              if (aa["status"] == 200) {
                if (aa["data"].length > 0) {
                  if (i == "c") {
                    this.images.push(aa["data"]);
                  } else {
                    this.images[i] = aa["data"];
                  }
                }
              }
              this.cd.detectChanges();
            });
          },
          err => {
            // Handle error
          }
        );
      }
    });

    buttonList.push({
      text: "取消",
      role: "取消",
      handler: () => { }
    });

    let actionSheet = this.actionSheet.create({ buttons: buttonList });
    actionSheet.present();
  }

  onHold(param) {
    let actionSheet = this.actionSheet.create({
      buttons: [
        {
          text: "重拍",
          role: "重拍",
          handler: () => {
            let i = this.images.indexOf(param);
            this.presentActionSheet(i);
          }
        },
        {
          text: "查看大图",
          role: "查看大图",
          handler: () => {
            let url: string = param;
            this.photoViewer.show(
              encodeURI(
                this.appConfig.IP_URL + this.appConfig.API.getUpload + url
              ).replace("%5C", "/"),
              null,
              { share: false }
            );
          }
        },
        {
          text: "删除",
          handler: () => {
            let i = this.images.indexOf(param);
            this.images.splice(i, 1);
          }
        },
        {
          text: "取消",
          role: "取消",
          handler: () => {
            //console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }

  queryParty() {
    if (this.rescuePartyName) {
      let param = {
        partyName: this.rescuePartyName
      };
      this.canSubmit = true;
      this.httpService.queryPartyByNameLk(param).subscribe(data => {
        if (data.status == 200) {
          this.emergencyRescueBean.rescuePartyId = data.data.id;
          this.canSubmit = true;
        } else {
          this.canSubmit = true;
          // const alertcc = this.alerc.create({
          //   // title: '',
          //   subTitle: "未能在系统中查到您填写的救援单位",
          //   buttons: ["确定"]
          // });
          // alertcc.present();
          return;
        }
      });
    }
  }
}
